package cn.tworice.scheduled;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Service
public class DynamicTaskService {

    private final ThreadPoolTaskScheduler taskScheduler;
    private final Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();

    public DynamicTaskService() {
        this.taskScheduler = new ThreadPoolTaskScheduler();
        this.taskScheduler.initialize();
    }

    /**
     * 添加任务
     * @param taskId 任务ID
     * @param task 任务
     * @param cronExpression cron表达式
     */
    public void addTask(String taskId, Runnable task, String cronExpression) {
        ScheduledFuture<?> scheduledTask = taskScheduler.schedule(task, new CronTrigger(cronExpression));
        tasks.put(taskId, scheduledTask);
    }

    /**
     * 添加任务
     * @param taskId 任务ID
     * @param task 任务
     * @param startTime 开始时间
     */
    public void addTask(String taskId, Runnable task, Date startTime) {
        ScheduledFuture<?> scheduledTask = taskScheduler.schedule(task, startTime);
        tasks.put(taskId, scheduledTask);
    }

    public void removeTask(String taskId) {
        ScheduledFuture<?> scheduledTask = tasks.get(taskId);
        if (scheduledTask != null) {
            scheduledTask.cancel(true);
            tasks.remove(taskId);
        }
    }

    /**
     * 更新任务
     * @param taskId 任务ID
     * @param task 任务
     * @param newCronExpression cron表达式
     */
    public void updateTask(String taskId, Runnable task, String newCronExpression) {
        removeTask(taskId);
        addTask(taskId, task, newCronExpression);
    }

    /**
     * 更新任务
     * @param taskId 任务ID
     * @param task 任务
     * @param startTime 开始时间
     */
    public void updateTask(String taskId, Runnable task, Date startTime) {
        removeTask(taskId);
        addTask(taskId, task, startTime);
    }

    /**
     * 判断这个任务是否存在
     * @param taskId 任务ID
     * @return 是否存在
     */
    public boolean taskExists(String taskId) {
        return tasks.containsKey(taskId);
    }
}

